package com.mk.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mk.springboot.mapper.UserMapper;
import com.mk.springboot.pojo.Category;
import com.mk.springboot.until.PageFactory;
import com.mk.springboot.pojo.User;
import com.mk.springboot.until.Result;
import com.mk.springboot.until.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

//@SuppressWarnings("rawtypes")
@Controller
public class UserController {

    @Autowired
    UserMapper userMapper;

    @RequestMapping("/user/list")
    @ResponseBody
    public PageFactory list(HttpServletRequest httpServletRequest) {
        String keyword = httpServletRequest.getParameter("keyword");
        Integer start = Integer.parseInt(httpServletRequest.getParameter("start"));
        Integer size = Integer.parseInt(httpServletRequest.getParameter("length"));
        Integer current = start / size + 1;

        PageFactory pageFac = new PageFactory();
        IPage<User> page = new Page<>(current, size);
        QueryWrapper qw = new QueryWrapper<User>();
        if (keyword != null) {
            qw.like("username", keyword);
            qw.or();
            qw.like("true_name", keyword);
        }
        userMapper.selectPage(page, qw);

        pageFac.setRecordsFiltered(page.getTotal());
        pageFac.setRecordsTotal(page.getTotal());
        pageFac.setData(page.getRecords());

        return pageFac;
    }

    @GetMapping("/user/edit")
    public String edit(Model model, HttpServletRequest httpServletRequest) {
        String id = httpServletRequest.getParameter("id");
        User user = userMapper.selectById(Integer.parseInt(id));
        model.addAttribute("user", user);
        return "/user/edit";
    }

    @PostMapping("/user/edit")
    @ResponseBody
    public Result edit(User user) {
        userMapper.updateById(user);
        return ResultUtil.success("成功修改用户: " + user.getUsername() + " 信息!");
    }

    @PostMapping("/user/add")
    @ResponseBody
    public Result add(User user) {
        userMapper.insert(user);
        return ResultUtil.success("成功添加用户：" + user.getUsername() + "信息!");
    }

    @GetMapping("/user/del")
    @ResponseBody
    public Result del(HttpServletRequest httpServletRequest) {
        String id = httpServletRequest.getParameter("id");
        userMapper.deleteById(Integer.parseInt(id));
        return ResultUtil.success("成功删除用户信息!");
    }
}
